<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - 我的个人博客</title>
    <link rel="stylesheet" href="assets/css/font-awesome.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f6fa;
            color: #333;
        }

        /* 侧边栏 */
        .sidebar {
            width: 260px;
            height: 100vh;
            background: #2c3e50;
            position: fixed;
            left: 0;
            top: 0;
            color: white;
            z-index: 1000;
            transition: transform 0.3s;
        }

        .sidebar-header {
            padding: 2rem 1.5rem;
            border-bottom: 1px solid #34495e;
        }

        .sidebar-title {
            font-size: 1.3rem;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .sidebar-menu {
            list-style: none;
            padding: 1rem 0;
        }

        .menu-item {
            margin-bottom: 0.5rem;
        }

        .menu-link {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            padding: 1rem 1.5rem;
            color: #bdc3c7;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        .menu-link:hover, .menu-link.active {
            background: #34495e;
            color: white;
            border-left-color: #3498db;
        }

        .menu-icon {
            width: 20px;
            text-align: center;
        }

        /* 主要内容区域 */
        .main-content {
            margin-left: 260px;
            padding: 0;
            min-height: 100vh;
        }

        /* 顶部栏 */
        .topbar {
            background: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 1.8rem;
            font-weight: bold;
            color: #2c3e50;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: #3498db;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .logout-btn {
            color: #e74c3c;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border: 1px solid #e74c3c;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .logout-btn:hover {
            background: #e74c3c;
            color: white;
        }

        /* 内容区域 */
        .content {
            padding: 2rem;
        }

        .content-section {
            display: none;
        }

        .content-section.active {
            display: block;
        }

        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 8px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }

        .card-title {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2c3e50;
        }

        /* 按钮 */
        .btn {
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-success {
            background: #27ae60;
            color: white;
        }

        .btn-success:hover {
            background: #229954;
        }

        .btn-warning {
            background: #f39c12;
            color: white;
        }

        .btn-warning:hover {
            background: #e67e22;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        .btn-sm {
            padding: 0.5rem 0.8rem;
            font-size: 0.9rem;
        }

        /* 表格 */
        .table-container {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }

        .table th,
        .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        .table tr:hover {
            background: #f8f9fa;
        }

        /* 状态标签 */
        .status-badge {
            padding: 0.3rem 0.8rem;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .status-published {
            background: #d4edda;
            color: #155724;
        }

        .status-draft {
            background: #fff3cd;
            color: #856404;
        }

        .status-hidden {
            background: #f8d7da;
            color: #721c24;
        }

        /* 搜索框 */
        .search-box {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            align-items: center;
        }

        .search-input {
            flex: 1;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }

        .search-input:focus {
            outline: none;
            border-color: #3498db;
        }

        /* 搜索结果样式 */
        .article-title-cell h4 {
            margin: 0 0 5px 0;
            font-size: 16px;
            font-weight: 500;
        }

        .article-summary {
            margin: 0;
            font-size: 14px;
            color: #666;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        /* 高亮样式 */
        mark {
            background-color: #ffeb3b !important;
            color: #333 !important;
            padding: 2px 4px;
            border-radius: 3px;
            font-weight: 500;
        }

        /* 分页 */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 0.5rem;
            margin-top: 2rem;
        }

        .page-btn {
            padding: 0.5rem 0.8rem;
            border: 1px solid #ddd;
            background: white;
            color: #666;
            text-decoration: none;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .page-btn:hover, .page-btn.active {
            background: #3498db;
            color: white;
            border-color: #3498db;
        }

        /* 统计卡片 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #3498db;
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #7f8c8d;
            font-size: 1rem;
        }

        .stat-icon {
            float: right;
            font-size: 2rem;
            color: #3498db;
            opacity: 0.7;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .mobile-menu-btn {
                display: block;
                background: none;
                border: none;
                font-size: 1.5rem;
                color: #2c3e50;
                cursor: pointer;
            }

            .content {
                padding: 1rem;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }

        .mobile-menu-btn {
            display: none;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 3rem;
            color: #666;
        }

        .loading i {
            font-size: 2rem;
            animation: spin 1s linear infinite;
            margin-bottom: 1rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #888;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #ddd;
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-title">
                <i class="fas fa-cog"></i>
                管理后台
            </div>
        </div>
        
        <ul class="sidebar-menu">
            <li class="menu-item">
                <a href="#dashboard" class="menu-link active" onclick="showSection('dashboard', this)">
                    <i class="fas fa-tachometer-alt menu-icon"></i>
                    <span>仪表盘</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="#articles" class="menu-link" onclick="showSection('articles', this)">
                    <i class="fas fa-file-alt menu-icon"></i>
                    <span>文章管理</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="#categories" class="menu-link" onclick="showSection('categories', this)">
                    <i class="fas fa-folder menu-icon"></i>
                    <span>分类管理</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="#tags" class="menu-link" onclick="showSection('tags', this)">
                    <i class="fas fa-tags menu-icon"></i>
                    <span>标签管理</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="blog.html" class="menu-link">
                    <i class="fas fa-home menu-icon"></i>
                    <span>回到博客</span>
                </a>
            </li>
        </ul>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
        <!-- 顶部栏 -->
        <div class="topbar">
            <div style="display: flex; align-items: center; gap: 1rem;">
                <button class="mobile-menu-btn" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="page-title" id="pageTitle">仪表盘</h1>
            </div>
            
            <div class="user-info">
                <div class="user-avatar" id="userAvatar">A</div>
                <span id="userName">管理员</span>
                <a href="login.html" class="logout-btn" onclick="logout()">
                    <i class="fas fa-sign-out-alt"></i>
                    退出
                </a>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content">
            <!-- 仪表盘 -->
            <div class="content-section active" id="dashboard">
                <div class="stats-grid">
                    <div class="stat-card">
                        <i class="fas fa-file-alt stat-icon"></i>
                        <div class="stat-value" id="totalArticles">0</div>
                        <div class="stat-label">总文章数</div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-eye stat-icon"></i>
                        <div class="stat-value" id="totalViews">0</div>
                        <div class="stat-label">总浏览量</div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-folder stat-icon"></i>
                        <div class="stat-value" id="totalCategories">0</div>
                        <div class="stat-label">分类数量</div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-tags stat-icon"></i>
                        <div class="stat-value" id="totalTags">0</div>
                        <div class="stat-label">标签数量</div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">最新文章</h2>
                        <a href="#articles" class="btn btn-primary" onclick="showSection('articles', document.querySelector('a[href=\'#articles\']'))">
                            <i class="fas fa-plus"></i>
                            新建文章
                        </a>
                    </div>
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>标题</th>
                                    <th>状态</th>
                                    <th>浏览量</th>
                                    <th>发布时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="recentArticlesTable">
                                <tr>
                                    <td colspan="5">
                                        <div class="loading">
                                            <i class="fas fa-spinner"></i>
                                            <p>加载中...</p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 文章管理 -->
            <div class="content-section" id="articles">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">文章管理</h2>
                        <button class="btn btn-primary" onclick="createArticle()">
                            <i class="fas fa-plus"></i>
                            新建文章
                        </button>
                    </div>
                    
                    <div class="search-box">
                        <input type="text" class="search-input" placeholder="搜索文章..." id="articleSearch" onkeypress="handleSearchKeyPress(event)">
                        <button class="btn btn-primary" onclick="searchArticles()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                    
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>标题</th>
                                    <th>分类</th>
                                    <th>状态</th>
                                    <th>浏览量</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="articlesTable">
                                <!-- 动态加载 -->
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pagination" id="articlesPagination">
                        <!-- 动态生成 -->
                    </div>
                </div>
            </div>

            <!-- 分类管理 -->
            <div class="content-section" id="categories">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">分类管理</h2>
                        <button class="btn btn-primary" onclick="createCategory()">
                            <i class="fas fa-plus"></i>
                            新建分类
                        </button>
                    </div>
                    <div id="categoriesContent">
                        <!-- 动态加载 -->
                    </div>
                </div>
            </div>

            <!-- 标签管理 -->
            <div class="content-section" id="tags">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">标签管理</h2>
                        <button class="btn btn-primary" onclick="createTag()">
                            <i class="fas fa-plus"></i>
                            新建标签
                        </button>
                    </div>
                    <div id="tagsContent">
                        <!-- 动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // API基础URL
        const API_BASE_URL = 'http://localhost:8080/api';
        
        // 当前用户信息
        let currentUser = null;
        let currentPage = 1;

        // 页面加载时初始化
        window.addEventListener('load', function() {
            checkAuth();
            loadDashboard();
        });

        // 检查用户权限
        function checkAuth() {
            const user = localStorage.getItem('user');
            if (!user) {
                alert('请先登录');
                window.location.href = 'login.html';
                return;
            }

            currentUser = JSON.parse(user);
            const roles = JSON.parse(localStorage.getItem('userRoles') || '[]');
            const hasAdminRole = roles.includes('ADMIN') || currentUser.role === 'admin';
            
            if (!hasAdminRole) {
                console.log('checkAuth权限检查失败:', { roles, userRole: currentUser.role });
                alert('权限不足，只有管理员才能访问后台');
                window.location.href = 'blog.html';
                return;
            }

            console.log('checkAuth权限检查通过:', { roles, userRole: currentUser.role });

            // 更新用户信息显示
            document.getElementById('userName').textContent = currentUser.username;
            document.getElementById('userAvatar').textContent = currentUser.username.charAt(0).toUpperCase();
        }

        // 显示指定的内容区域
        function showSection(sectionId, linkElement) {
            // 隐藏所有内容区域
            document.querySelectorAll('.content-section').forEach(section => {
                section.classList.remove('active');
            });

            // 显示指定的内容区域
            document.getElementById(sectionId).classList.add('active');

            // 更新菜单状态
            document.querySelectorAll('.menu-link').forEach(link => {
                link.classList.remove('active');
            });
            linkElement.classList.add('active');

            // 更新页面标题
            const titles = {
                'dashboard': '仪表盘',
                'articles': '文章管理',
                'categories': '分类管理',
                'tags': '标签管理'
            };
            document.getElementById('pageTitle').textContent = titles[sectionId] || '管理后台';

            // 加载对应内容
            switch(sectionId) {
                case 'dashboard':
                    loadDashboard();
                    break;
                case 'articles':
                    loadArticles();
                    break;
                case 'categories':
                    loadCategories();
                    break;
                case 'tags':
                    loadTags();
                    break;
            }
        }

        // 加载仪表盘数据
        async function loadDashboard() {
            try {
                // 调用真实的仪表盘统计API
                const response = await fetchWithAuth(`${API_BASE_URL}/admin/dashboard`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    if (result.code === 0) {
                        const data = result.data;
                        
                        // 更新统计数据
                        document.getElementById('totalArticles').textContent = data.totalArticles || '0';
                        document.getElementById('totalViews').textContent = formatNumber(data.totalViews || 0);
                        document.getElementById('totalCategories').textContent = data.totalCategories || '0';
                        document.getElementById('totalTags').textContent = data.totalTags || '0';
                        
                        console.log('仪表盘数据加载成功:', data);
                    } else {
                        console.error('获取仪表盘数据失败:', result.message);
                        // 使用默认值
                        setDefaultDashboardData();
                    }
                } else {
                    console.error('API请求失败:', response.status);
                    setDefaultDashboardData();
                }

                // 加载最新文章
                loadRecentArticles();

            } catch (error) {
                console.error('加载仪表盘数据失败:', error);
                setDefaultDashboardData();
            }
        }
        
        // 设置默认仪表盘数据
        function setDefaultDashboardData() {
            document.getElementById('totalArticles').textContent = '0';
            document.getElementById('totalViews').textContent = '0';
            document.getElementById('totalCategories').textContent = '0';
            document.getElementById('totalTags').textContent = '0';
        }
        
        // 格式化数字显示
        function formatNumber(num) {
            if (num >= 1000) {
                return (num / 1000).toFixed(1) + 'k';
            }
            return num.toString();
        }

        // 加载最新文章
        async function loadRecentArticles() {
            try {
                const response = await fetch(`${API_BASE_URL}/blog/articles?page=1&size=5`);
                const result = await response.json();

                if (result.code === 0) {
                    const articles = result.data.records || [];
                    renderRecentArticles(articles);
                } else {
                    throw new Error(result.message);
                }

            } catch (error) {
                console.error('加载最新文章失败:', error);
                document.getElementById('recentArticlesTable').innerHTML = `
                    <tr>
                        <td colspan="5" class="empty-state">
                            <i class="fas fa-exclamation-triangle"></i>
                            <p>加载失败</p>
                        </td>
                    </tr>
                `;
            }
        }

        // 渲染最新文章
        function renderRecentArticles(articles) {
            const tbody = document.getElementById('recentArticlesTable');
            
            if (articles.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="5" class="empty-state">
                            <i class="fas fa-file-alt"></i>
                            <p>暂无文章</p>
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = articles.map(article => `
                <tr>
                    <td><strong>${article.title}</strong></td>
                    <td><span class="status-badge status-${getStatusClass(article.status)}">${getStatusText(article.status)}</span></td>
                    <td>${article.viewCount || 0}</td>
                    <td>${formatDate(article.publishTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editArticle(${article.id})">
                            <i class="fas fa-edit"></i>
                            编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteArticle(${article.id})">
                            <i class="fas fa-trash"></i>
                            删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 加载文章列表
        async function loadArticles(page = 1) {
            try {
                const response = await fetchWithAuth(`${API_BASE_URL}/admin/articles?page=${page}&size=10`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    if (result.code === 0) {
                        const articles = result.data.articles || [];
                        renderArticlesTable(articles);
                        console.log('文章列表加载成功');
                    } else {
                        throw new Error(result.message);
                    }
                } else {
                    throw new Error('请求失败');
                }
            } catch (error) {
                console.error('加载文章列表失败:', error);
            document.getElementById('articlesTable').innerHTML = `
                <tr>
                        <td colspan="7" class="empty-state">
                            <i class="fas fa-exclamation-triangle"></i>
                            <p>加载失败：${error.message}</p>
                    </td>
                </tr>
            `;
            }
        }
        
        // 渲染文章表格
        function renderArticlesTable(articles) {
            const tbody = document.getElementById('articlesTable');
            
            if (articles.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="empty-state">
                            <i class="fas fa-file-alt"></i>
                            <p>暂无文章</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            tbody.innerHTML = articles.map(article => `
                <tr>
                    <td>${article.id}</td>
                    <td><strong>${article.title}</strong></td>
                    <td>${article.category || '未分类'}</td>
                    <td><span class="status-badge status-${getStatusClass(article.status)}">${getStatusText(article.status)}</span></td>
                    <td>${article.viewCount || 0}</td>
                    <td>${formatDate(article.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editArticle(${article.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="toggleArticleStatus(${article.id}, ${article.status})" title="${article.status === 1 ? '隐藏' : '发布'}">
                            <i class="fas fa-${article.status === 1 ? 'eye-slash' : 'eye'}"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteArticle(${article.id})" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 加载分类列表
        async function loadCategories() {
            try {
                const response = await fetchWithAuth(`${API_BASE_URL}/admin/categories`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    if (result.code === 0) {
                        const categories = result.data.categories || [];
                        renderCategoriesTable(categories);
                        console.log('分类列表加载成功');
                    } else {
                        throw new Error(result.message);
                    }
                } else {
                    throw new Error('请求失败');
                }
            } catch (error) {
                console.error('加载分类列表失败:', error);
            document.getElementById('categoriesContent').innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>加载失败：${error.message}</p>
                    </div>
                `;
            }
        }
        
        // 渲染分类表格
        function renderCategoriesTable(categories) {
            const container = document.getElementById('categoriesContent');
            
            if (categories.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-folder"></i>
                        <p>暂无分类</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = `
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>分类名称</th>
                                <th>文章数量</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${categories.map(category => `
                                <tr>
                                    <td>${category.id}</td>
                                    <td><strong>${category.name}</strong></td>
                                    <td>${category.articleCount || 0}</td>
                                    <td>${formatDate(category.createTime)}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editCategory(${category.id}, '${category.name}')" title="编辑">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteCategory(${category.id}, '${category.name}')" title="删除">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 加载标签列表
        async function loadTags() {
            try {
                const response = await fetchWithAuth(`${API_BASE_URL}/admin/tags`);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    if (result.code === 0) {
                        const tags = result.data.tags || [];
                        renderTagsTable(tags);
                        console.log('标签列表加载成功');
                    } else {
                        throw new Error(result.message);
                    }
                } else {
                    throw new Error('请求失败');
                }
            } catch (error) {
                console.error('加载标签列表失败:', error);
            document.getElementById('tagsContent').innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>加载失败：${error.message}</p>
                    </div>
                `;
            }
        }
        
        // 渲染标签表格
        function renderTagsTable(tags) {
            const container = document.getElementById('tagsContent');
            
            if (tags.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-tags"></i>
                        <p>暂无标签</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = `
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>标签名称</th>
                                <th>颜色</th>
                                <th>文章数量</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tags.map(tag => `
                                <tr>
                                    <td>${tag.id}</td>
                                    <td>
                                        <span class="tag-badge" style="background-color: ${tag.color}; color: white; padding: 0.2rem 0.5rem; border-radius: 4px;">
                                            ${tag.name}
                                        </span>
                                    </td>
                                    <td>
                                        <span style="display: inline-block; width: 20px; height: 20px; background-color: ${tag.color}; border-radius: 50%; margin-right: 0.5rem;"></span>
                                        ${tag.color}
                                    </td>
                                    <td>${tag.articleCount || 0}</td>
                                    <td>${formatDate(tag.createTime)}</td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="editTag(${tag.id}, '${tag.name}', '${tag.color}')" title="编辑">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteTag(${tag.id}, '${tag.name}')" title="删除">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 获取状态样式类
        function getStatusClass(status) {
            const statusMap = {
                0: 'draft',
                1: 'published',
                2: 'hidden'
            };
            return statusMap[status] || 'draft';
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                0: '草稿',
                1: '已发布',
                2: '已隐藏'
            };
            return statusMap[status] || '未知';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            return new Date(dateString).toLocaleDateString('zh-CN');
        }

        // 切换侧边栏（移动端）
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('open');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('user');
                window.location.href = 'login.html';
            }
        }

        // 文章管理功能
        function createArticle() {
            window.open('editor.html', '_blank');
        }

        function editArticle(id) {
            window.open(`editor.html?id=${id}`, '_blank');
        }

        async function deleteArticle(id) {
            if (confirm('确定要删除这篇文章吗？此操作不可恢复！')) {
                try {
                    const response = await fetchWithAuth(`${API_BASE_URL}/admin/articles/${id}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.code === 0) {
                            alert('文章删除成功！');
                            loadArticles(); // 重新加载列表
                        } else {
                            alert('删除失败：' + result.message);
                        }
                    } else {
                        alert('删除失败：网络错误');
                    }
                } catch (error) {
                    console.error('删除文章失败:', error);
                    alert('删除失败：' + error.message);
                }
            }
        }

        async function toggleArticleStatus(id, currentStatus) {
            const newStatus = currentStatus === 1 ? 2 : 1; // 1-发布, 2-隐藏
            const action = newStatus === 1 ? '发布' : '隐藏';
            
            if (confirm(`确定要${action}这篇文章吗？`)) {
                try {
                    const response = await fetchWithAuth(`${API_BASE_URL}/admin/articles/${id}/status`, {
                        method: 'PUT',
                        body: JSON.stringify({ status: newStatus })
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.code === 0) {
                            alert(`文章${action}成功！`);
                            loadArticles(); // 重新加载列表
                        } else {
                            alert(`${action}失败：` + result.message);
                        }
                    } else {
                        alert(`${action}失败：网络错误`);
                    }
                } catch (error) {
                    console.error(`${action}文章失败:`, error);
                    alert(`${action}失败：` + error.message);
                }
            }
        }

        function searchArticles() {
            const keyword = document.getElementById('articleSearch').value.trim();
            if (keyword) {
                console.log('搜索关键词:', keyword);
                // 调用后端搜索API
                performSearch(keyword);
            } else {
                loadArticles(); // 重新加载全部文章
            }
        }

        // 执行搜索
        function performSearch(keyword) {
            const tbody = document.getElementById('articlesTable');
            tbody.innerHTML = `
                <tr>
                    <td colspan="6">
                        <div class="loading">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>搜索中...</p>
                        </div>
                    </td>
                </tr>
            `;

            const token = localStorage.getItem('token');
            
            // 使用后端的搜索API
            fetch(`/api/blog/search?keyword=${encodeURIComponent(keyword)}&page=1&size=50`, {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    displaySearchResults(data.data.articles, keyword);
                } else {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 20px; color: #ff4444;">
                                搜索失败：${data.message}
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                console.error('搜索出错:', error);
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 20px; color: #ff4444;">
                            搜索出错，请稍后重试
                        </td>
                    </tr>
                `;
            });
        }

        // 显示搜索结果
        function displaySearchResults(articles, keyword) {
            const tbody = document.getElementById('articlesTable');
            
            if (!articles || articles.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 20px; color: #666;">
                            <i class="fas fa-search" style="font-size: 48px; margin-bottom: 10px; opacity: 0.5;"></i>
                            <br>
                            没有找到关键词 "${keyword}" 相关的文章
                            <br>
                            <button class="btn btn-secondary" onclick="clearSearch()" style="margin-top: 10px;">
                                <i class="fas fa-times"></i> 清除搜索
                            </button>
                        </td>
                    </tr>
                `;
                return;
            }

            let html = '';
            articles.forEach(article => {
                // 高亮搜索关键词
                const highlightedTitle = highlightKeyword(article.title || '', keyword);
                const highlightedSummary = highlightKeyword(article.summary || '', keyword);
                
                html += `
                    <tr>
                        <td>
                            <div class="article-title-cell">
                                <h4>${highlightedTitle}</h4>
                                <p class="article-summary">${highlightedSummary}</p>
                            </div>
                        </td>
                        <td>
                            <span class="status ${article.status === 1 ? 'published' : 'draft'}">
                                ${getStatusText(article.status)}
                            </span>
                        </td>
                        <td>${article.viewCount || 0}</td>
                        <td>${article.likeCount || 0}</td>
                        <td>${formatDateTime(article.createTime)}</td>
                        <td>
                            <button class="btn btn-primary btn-sm" onclick="editArticle(${article.id})">
                                <i class="fas fa-edit"></i>
                                编辑
                            </button>
                            <button class="btn btn-info btn-sm" onclick="viewArticle(${article.id})" style="margin: 0 5px;">
                                <i class="fas fa-eye"></i>
                                预览
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="deleteArticle(${article.id})">
                                <i class="fas fa-trash"></i>
                                删除
                            </button>
                        </td>
                    </tr>
                `;
            });

            // 添加搜索结果提示
            html = `
                <tr style="background-color: #e3f2fd;">
                    <td colspan="6" style="text-align: center; padding: 10px; color: #1976d2;">
                        <i class="fas fa-search"></i>
                        找到 <strong>${articles.length}</strong> 篇包含 "<strong>${keyword}</strong>" 的文章
                        <button class="btn btn-secondary btn-sm" onclick="clearSearch()" style="margin-left: 10px;">
                            <i class="fas fa-times"></i> 清除搜索
                        </button>
                    </td>
                </tr>
            ` + html;

            tbody.innerHTML = html;
        }

        // 清除搜索
        function clearSearch() {
            document.getElementById('articleSearch').value = '';
            loadArticles();
        }

        // 高亮关键词
        function highlightKeyword(text, keyword) {
            if (!text || !keyword) return text;
            
            const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi');
            return text.replace(regex, '<mark style="background-color: #ffeb3b; color: #333;">$1</mark>');
        }

        // 转义正则表达式特殊字符
        function escapeRegExp(string) {
            return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }

        // 处理搜索框Enter键事件
        function handleSearchKeyPress(event) {
            if (event.key === 'Enter') {
                searchArticles();
            }
        }

        // 分类管理功能
        function createCategory() {
            const name = prompt('请输入分类名称：');
            if (name && name.trim()) {
                saveCategory(null, name.trim());
            }
        }

        function editCategory(id, currentName) {
            const name = prompt('请输入新的分类名称：', currentName);
            if (name && name.trim() && name.trim() !== currentName) {
                saveCategory(id, name.trim());
            }
        }

        async function saveCategory(id, name) {
            try {
                const url = id ? `${API_BASE_URL}/admin/categories/${id}` : `${API_BASE_URL}/admin/categories`;
                const method = id ? 'PUT' : 'POST';
                
                const response = await fetchWithAuth(url, {
                    method: method,
                    body: JSON.stringify({ name: name })
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        alert(`分类${id ? '更新' : '创建'}成功！`);
                        loadCategories(); // 重新加载列表
                    } else {
                        alert(`操作失败：` + result.message);
                    }
                } else {
                    alert('操作失败：网络错误');
                }
            } catch (error) {
                console.error('保存分类失败:', error);
                alert('操作失败：' + error.message);
            }
        }

        async function deleteCategory(id, name) {
            if (confirm(`确定要删除分类"${name}"吗？此操作不可恢复！`)) {
                try {
                    const response = await fetchWithAuth(`${API_BASE_URL}/admin/categories/${id}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.code === 0) {
                            alert('分类删除成功！');
                            loadCategories(); // 重新加载列表
                        } else {
                            alert('删除失败：' + result.message);
                        }
                    } else {
                        alert('删除失败：网络错误');
                    }
                } catch (error) {
                    console.error('删除分类失败:', error);
                    alert('删除失败：' + error.message);
                }
            }
        }

        // 标签管理功能
        function createTag() {
            const name = prompt('请输入标签名称：');
            if (name && name.trim()) {
                const color = prompt('请输入标签颜色（hex格式，如 #ff0000）：', '#007bff');
                if (color) {
                    saveTag(null, name.trim(), color);
                }
            }
        }

        function editTag(id, currentName, currentColor) {
            const name = prompt('请输入新的标签名称：', currentName);
            if (name && name.trim()) {
                const color = prompt('请输入标签颜色（hex格式）：', currentColor);
                if (color) {
                    saveTag(id, name.trim(), color);
                }
            }
        }

        async function saveTag(id, name, color) {
            try {
                const url = id ? `${API_BASE_URL}/admin/tags/${id}` : `${API_BASE_URL}/admin/tags`;
                const method = id ? 'PUT' : 'POST';
                
                const response = await fetchWithAuth(url, {
                    method: method,
                    body: JSON.stringify({ name: name, color: color })
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        alert(`标签${id ? '更新' : '创建'}成功！`);
                        loadTags(); // 重新加载列表
                    } else {
                        alert(`操作失败：` + result.message);
                    }
                } else {
                    alert('操作失败：网络错误');
                }
            } catch (error) {
                console.error('保存标签失败:', error);
                alert('操作失败：' + error.message);
            }
        }

        async function deleteTag(id, name) {
            if (confirm(`确定要删除标签"${name}"吗？此操作不可恢复！`)) {
                try {
                    const response = await fetchWithAuth(`${API_BASE_URL}/admin/tags/${id}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.code === 0) {
                            alert('标签删除成功！');
                            loadTags(); // 重新加载列表
                        } else {
                            alert('删除失败：' + result.message);
                        }
                    } else {
                        alert('删除失败：网络错误');
                    }
                } catch (error) {
                    console.error('删除标签失败:', error);
                    alert('删除失败：' + error.message);
                }
            }
        }

        // 创建带认证头的fetch请求
        function fetchWithAuth(url, options = {}) {
            const token = localStorage.getItem('token');
            
            if (!token) {
                throw new Error('未找到认证token');
            }
            
            options.headers = {
                ...options.headers,
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            };
            
            return fetch(url, options);
        }

        // 清除认证数据
        function clearAuthData() {
            localStorage.removeItem('user');
            localStorage.removeItem('token');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userRoles');
            localStorage.removeItem('userPermissions');
        }

        // 检查管理员权限
        function checkAdminAuth() {
            const user = localStorage.getItem('user');
            const token = localStorage.getItem('token');
            const roles = JSON.parse(localStorage.getItem('userRoles') || '[]');
            
            if (!user || !token) {
                alert('请先登录');
                window.location.href = 'login.html';
                return false;
            }
            
            // 解析用户信息检查角色
            const userInfo = JSON.parse(user);
            const hasAdminRole = roles.includes('ADMIN') || userInfo.role === 'admin';
            
            if (!hasAdminRole) {
                console.log('权限检查失败:', { roles, userRole: userInfo.role });
                alert('权限不足，无法访问管理后台');
                window.location.href = 'blog.html';
                return false;
            }
            
            console.log('权限检查通过:', { roles, userRole: userInfo.role });
            
            // 检查token是否过期
            if (isTokenExpired(token)) {
                alert('登录已过期，请重新登录');
                clearAuthData();
                window.location.href = 'login.html';
                return false;
            }
            
            return true;
        }

        // 检查token是否过期
        function isTokenExpired(token) {
            try {
                const payload = JSON.parse(atob(token.split('.')[1]));
                const currentTime = Date.now() / 1000;
                return payload.exp < currentTime;
            } catch (e) {
                console.error('解析token失败:', e);
                return true;
            }
        }

        // 加载真实的仪表盘数据
        async function loadRealDashboard() {
            try {
                const response = await fetchWithAuth('/api/admin/dashboard');
                
                if (response.status === 401) {
                    alert('登录已过期，请重新登录');
                    clearAuthData();
                    window.location.href = 'login.html';
                    return;
                } else if (response.status === 403) {
                    alert('权限不足，无法访问管理后台');
                    window.location.href = 'blog.html';
                    return;
                }
                
                const result = await response.json();
                
                if (result.code === 0) {
                    const data = result.data;
                    console.log('仪表盘数据:', data);
                    // 更新页面数据（如果需要的话）
                    // document.getElementById('totalUsers').textContent = data.totalUsers || '0';
                    // document.getElementById('totalArticles').textContent = data.totalArticles || '0';
                    // document.getElementById('totalViews').textContent = data.totalViews || '0';
                    // document.getElementById('todayViews').textContent = data.todayViews || '0';
                } else {
                    console.error('获取仪表盘数据失败:', result.message);
                }
                
            } catch (error) {
                console.error('加载仪表盘数据失败:', error);
            }
        }

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('管理后台页面加载完成');
            
            // 检查管理员权限
            if (checkAdminAuth()) {
                console.log('权限验证通过，加载仪表盘数据');
                loadRealDashboard();
                
                // 显示仪表盘内容
                showSection('dashboard');
            }
        });
    </script>
</body>
</html>
